package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.BBusiness;
import com.sxbbc.common.core.entity.jz.ProcBrandApply;
import com.sxbbc.common.core.entity.jz.ProcBrandInfo;
import com.sxbbc.common.core.entity.jz.ProcFirstClassifyMain;
import com.sxbbc.common.core.enums.BrandTypeEnums;
import com.sxbbc.common.core.mapper.jz.BBusinessMapper;
import com.sxbbc.common.core.mapper.jz.ProcBrandApplyMapper;
import com.sxbbc.common.core.mapper.jz.ProcBrandInfoMapper;
import com.sxbbc.common.core.mapper.jz.ProcFirstClassifyMainMapper;
import com.sxbbc.common.core.service.IProcBrandApplyService;
import com.sxbbc.common.core.utils.BasePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 品牌申请记录表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-05-06
 */
@SuppressWarnings("all")
@Service
public class ProcBrandApplyServiceImpl extends ServiceImpl<ProcBrandApplyMapper, ProcBrandApply> implements IProcBrandApplyService {

    @Autowired
    private ProcFirstClassifyMainMapper firstClassifyMainMapper;
    @Autowired
    private ProcBrandInfoMapper procBrandInfoMapper;
    @Autowired
    private BBusinessMapper businessMapper;

    private static final int DEFAULT_STATUS = 0;

    @Override
    public Page<ProcBrandApply> queryBrandApplyList(BasePage<ProcBrandApply> page, ProcBrandApply apply) {
        QueryWrapper<ProcBrandApply> wrapper = new QueryWrapper<>();
        if (apply.getStatus() != null && apply.getStatus() != DEFAULT_STATUS) {
            wrapper.eq("status", apply.getStatus());
        }
        if (apply.getTargetId() != null && apply.getTargetId() != DEFAULT_STATUS) {
            wrapper.eq("target_id", apply.getTargetId());
        }
        if (page.isPaging()) {
            super.page(page, wrapper);
        } else {
            List<ProcBrandApply> list = super.list(wrapper);
            page.setRecords(list);
        }
        StringBuffer name = new StringBuffer();
        String[] ids = {};
        for (ProcBrandApply a : page.getRecords()) {
            a.setTargetName(BrandTypeEnums.getName(a.getType()));
            if (StringUtils.isNotBlank(a.getFirstIds())) {
                ids = a.getFirstIds().split(",");
                for (int i = 0; i < ids.length; i++) {
                    ProcFirstClassifyMain first = firstClassifyMainMapper.selectById(Integer.parseInt(ids[i]));
                    if (i < ids.length - 1) {
                        name.append(first.getName()).append(",");
                    } else {
                        name.append(first.getName());
                    }
                }
                a.setClassifyName(name.toString());
            }
        }
        return page;
    }

    @Override
    public RestResponse handleBrandApply(Integer id, Integer status) {
        CalcuUtils cal = CalcuUtils.getInstance();
        ProcBrandApply apply = super.getById(id);
        if (apply == null) {
            return GetRest.getFail("该申请记录不存在");
        }
        if (!cal.isEquals(StaticUtils.STATUS_APPLY, apply.getStatus())) {
            return GetRest.getFail("当前品牌申请不是待审核状态");
        }
        boolean save = false;
        // 更新品牌申请记录的状态
        apply.setStatus(status);
        save = super.updateById(apply);
        // 通过审核时，新增品牌信息
        if (cal.isEquals(StaticUtils.STATUS_SUCCESS, status)) {
            ProcBrandInfo info = new ProcBrandInfo();
            info.setCreatetime(new Date());
            info.setName(apply.getName());
            info.setStatus(StaticUtils.STATUS_YES);
            info.setUrl(apply.getUrl());
            info.setType(apply.getType());
            info.setTargetId(apply.getTargetId());
            info.setFirstIds("," + apply.getFirstIds() + ",");
            procBrandInfoMapper.insert(info);
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("createtime");
        List<ProcBrandInfo> list = procBrandInfoMapper.selectList(wrapper);
        ProcBrandInfo brandInfo = null;
        if (!CollectionUtils.isEmpty(list)) {
            brandInfo = list.get(0);
        }
        // 更新商家的品牌id
        if (cal.isEquals(brandInfo.getType(), BrandTypeEnums.BUSINESS.getId())) {
            BBusiness business = businessMapper.selectById(brandInfo.getTargetId());
            business.setBrandIds(business.getBrandIds() + "," + brandInfo.getId());
            businessMapper.updateById(business);
        }
        if (!save) {
            throw new ThrowJsonException("品牌申请记录处理失败");
        }
        return GetRest.getSuccess("处理成功");
    }
}
